#!/bin/bash

# git_pull_all_test.sh - git_pull_all 脚本单元测试
#
# 用途: 测试 git_pull_all 脚本的各个功能模块
# 作者: Claude
# 版本: 1.0

set -euo pipefail

# 测试环境设置
readonly TEST_DIR="/tmp/git_pull_all_test"
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../scripts" && pwd)"
readonly MAIN_SCRIPT="$SCRIPT_DIR/git_pull_all.sh"

# 颜色定义
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[0;33m'
readonly BLUE='\033[0;34m'
readonly NC='\033[0m' # No Color

# 测试计数器
total_tests=0
passed_tests=0
failed_tests=0

# 初始化测试环境
setup_test_environment() {
    echo -e "${BLUE}设置测试环境...${NC}"
    
    # 创建测试目录
    mkdir -p "$TEST_DIR"
    cd "$TEST_DIR"
    
    # 创建模拟的Git仓库
    create_mock_git_repos
    
    # 创建脚本副本
    cp "$MAIN_SCRIPT" ./git_pull_all.sh
    
    echo -e "${GREEN}测试环境设置完成${NC}"
}

# 创建模拟的Git仓库
create_mock_git_repos() {
    echo "创建模拟Git仓库..."
    
    # 创建有效的Git仓库
    mkdir -p valid_repo1 valid_repo2
    
    # 创建.git文件夹
    cd valid_repo1
    mkdir .git
    echo "ref: refs/heads/main" > .git/HEAD
    cd ..
    
    cd valid_repo2
    mkdir .git
    echo "ref: refs/heads/master" > .git/HEAD
    cd ..
    
    # 创建非Git目录
    mkdir -p non_repo1 non_repo2
    
    # 创建嵌套目录
    mkdir -p nested/valid_repo
    cd nested/valid_repo
    mkdir .git
    echo "ref: refs/heads/main" > .git/HEAD
    cd ../../..
    
    echo "模拟Git仓库创建完成"
}

# 清理测试环境
cleanup_test_environment() {
    echo -e "${BLUE}清理测试环境...${NC}"
    
    # 返回到原目录
    cd /
    
    # 删除测试目录
    rm -rf "$TEST_DIR"
    
    echo -e "${GREEN}测试环境清理完成${NC}"
}

# 测试结果输出
test_result() {
    local test_name="$1"
    local expected="$2"
    local actual="$3"
    
    total_tests=$((total_tests + 1))
    
    if [[ "$expected" == "$actual" ]]; then
        echo -e "${GREEN}✓ ${test_name}${NC}"
        passed_tests=$((passed_tests + 1))
        return 0
    else
        echo -e "${RED}✗ ${test_name}${NC}"
        echo -e "  预期: $expected"
        echo -e "  实际: $actual"
        failed_tests=$((failed_tests + 1))
        return 1
    fi
}

# 测试detect_git_repository函数
test_detect_git_repository() {
    echo -e "\n${BLUE}测试 detect_git_repository 函数...${NC}"
    
    # 测试有效Git仓库
    source ./git_pull_all.sh
    local result
    result=$(detect_git_repository "$TEST_DIR/valid_repo1")
    test_result "检测有效Git仓库" "0" "$result"
    
    # 测试非Git目录
    result=$(detect_git_repository "$TEST_DIR/non_repo1")
    test_result "检测非Git目录" "1" "$result"
    
    # 测试不存在的路径
    result=$(detect_git_repository "/non/existent/path")
    test_result "检测不存在的路径" "1" "$result"
}

# 测试traverse_directories函数
test_traverse_directories() {
    echo -e "\n${BLUE}测试 traverse_directories 函数...${NC}"
    
    source ./git_pull_all.sh
    
    # 测试正常目录遍历
    local -a subdirs
    if readarray -t subdirs < <(traverse_directories "$TEST_DIR"); then
        local expected_dirs=("non_repo1" "non_repo2" "valid_repo1" "valid_repo2")
        local found=false
        
        for expected in "${expected_dirs[@]}"; do
            if printf '%s\n' "${subdirs[@]}" | grep -q "^$expected$"; then
                found=true
                break
            fi
        done
        
        test_result "遍历目录" "true" "$found"
    else
        test_result "遍历目录" "true" "false"
    fi
    
    # 测试不存在的目录
    result=$(traverse_directories "/non/existent/path")
    test_result "遍历不存在的目录" "1" "$?"
}

# 测试get_remote_branch函数
test_get_remote_branch() {
    echo -e "\n${BLUE}测试 get_remote_branch 函数...${NC}"
    
    source ./git_pull_all.sh
    
    # 测试main分支优先检测
    cd "$TEST_DIR/valid_repo1"
    result=$(get_remote_branch "$TEST_DIR/valid_repo1")
    test_result "检测main分支" "origin/main" "$result"
    
    # 测试master分支检测
    cd "$TEST_DIR/valid_repo2"
    result=$(get_remote_branch "$TEST_DIR/valid_repo2")
    test_result "检测master分支" "origin/master" "$result"
    
    # 测试非Git目录
    result=$(get_remote_branch "$TEST_DIR/non_repo1")
    test_result "非Git目录检测" "1" "$?"
}

# 测试generate_statistics函数
test_generate_statistics() {
    echo -e "\n${BLUE}测试 generate_statistics 函数...${NC}"
    
    source ./git_pull_all.sh
    
    # 创建临时状态文件
    echo "success" > "/tmp/git_pull_status_valid_repo1.tmp"
    echo "failure" > "/tmp/git_pull_status_valid_repo2.tmp"
    
    # 测试统计函数
    local result
    result=$(generate_statistics "$TEST_DIR/valid_repo1" "$TEST_DIR/valid_repo2" "$TEST_DIR/non_repo1")
    local exit_code=$?
    
    # 清理临时文件
    rm -f "/tmp/git_pull_status_*.tmp"
    
    test_result "生成统计报告" "0" "$exit_code"
}

# 测试错误处理函数
test_error_handling() {
    echo -e "\n${BLUE}测试错误处理函数...${NC}"
    
    source ./git_pull_all.sh
    
    # 测试网络错误处理
    result=$(handle_network_error "test_repo")
    if echo "$result" | grep -q "网络错误"; then
        test_result "网络错误处理" "true" "true"
    else
        test_result "网络错误处理" "true" "false"
    fi
    
    # 测试认证错误处理
    result=$(handle_auth_error "test_repo")
    if echo "$result" | grep -q "认证错误"; then
        test_result "认证错误处理" "true" "true"
    else
        test_result "认证错误处理" "true" "false"
    fi
    
    # 测试权限错误处理
    result=$(handle_permission_error "test_repo")
    if echo "$result" | grep -q "权限错误"; then
        test_result "权限错误处理" "true" "true"
    else
        test_result "权限错误处理" "true" "false"
    fi
}

# 运行所有测试
run_all_tests() {
    echo -e "${BLUE}开始运行所有测试...${NC}"
    echo "=================================="
    
    setup_test_environment
    
    # 运行各个测试函数
    test_detect_git_repository
    test_traverse_directories
    test_get_remote_branch
    test_generate_statistics
    test_error_handling
    
    cleanup_test_environment
    
    # 输出测试结果汇总
    echo -e "\n${BLUE}测试结果汇总${NC}"
    echo "=================================="
    echo "总测试数: $total_tests"
    echo -e "${GREEN}通过: $passed_tests${NC}"
    echo -e "${RED}失败: $failed_tests${NC}"
    
    if [[ $failed_tests -eq 0 ]]; then
        echo -e "${GREEN}所有测试通过！${NC}"
        exit 0
    else
        echo -e "${RED}有 $failed_tests 个测试失败${NC}"
        exit 1
    fi
}

# 显示测试帮助信息
show_help() {
    cat << EOF
git_pull_all_test.sh - git_pull_all 脚本单元测试

用法: $0 [选项]

选项:
    -h, --help      显示此帮助信息
    --run-tests     运行所有测试

示例:
    $0 --run-tests    运行所有测试并显示结果
EOF
}

# 主函数
main() {
    case "${1:-}" in
        -h|--help)
            show_help
            exit 0
            ;;
        --run-tests|"")
            run_all_tests
            ;;
        *)
            echo "未知选项: $1"
            show_help
            exit 1
            ;;
    esac
}

main "$@"